<template>
	<view class="content">
		<view class="form-container">
			<uni-forms :model="form" ref="uForm" :rules="rules" label-position="top" validate-trigger="submit">
				<uni-forms-item label="房间号" name="room_number" required>
					<uni-easyinput v-model="form.room_number" placeholder="请输入房间号" />
				</uni-forms-item>
				
				<uni-forms-item label="房间价格" name="price" required>
					<uni-easyinput v-model="form.price" placeholder="请输入月租金价格" type="number" />
				</uni-forms-item>
				
				<uni-forms-item label="户型" name="room_type" required>
					<uni-easyinput v-model="form.room_type" placeholder="请输入户型，如：一室一厅" />
				</uni-forms-item>
				
				<uni-forms-item label="房间图片" name="images">
					<view class="upload-box">
						<u-upload :file-list="fileList" name="files" 
							:max-count="9" @after-read="afterRead" 
							@delete="deleteImage" :show-upload="fileList.length < 9"></u-upload>
					</view>
				</uni-forms-item>
				
				<uni-forms-item label="家具配置" name="furniture_list">
					<view class="furniture-box">
						<view class="furniture-item" v-for="(item, index) in form.furniture_list" :key="index">
							<uni-easyinput v-model="form.furniture_list[index]" />
							<view class="delete-btn" @click="deleteFurniture(index)">
								<uni-icons type="close" size="20" color="#999"></uni-icons>
							</view>
						</view>
						<button size="mini" class="add-btn" @click="addFurniture">添加家具</button>
					</view>
				</uni-forms-item>
				
				<uni-forms-item label="房间简介" name="introduction">
					<uni-easyinput type="textarea" v-model="form.introduction" placeholder="请输入房间简介" :autoHeight="true" />
				</uni-forms-item>
			</uni-forms>
			
			<view class="submit-btn">
				<u-button type="primary" text="保存修改" @click="submitForm"></u-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue';
	
	// 表单数据
	const form = reactive({
		room_id: '',
		floor_id: '',
		room_number: '',
		price: '',
		room_type: '',
		images: [],
		furniture_list: [],
		introduction: ''
	});
	
	// 表单校验规则
	const rules = {
		room_number: {
			rules: [{ required: true, errorMessage: '请输入房间号' }]
		},
		price: {
			rules: [
				{ required: true, errorMessage: '请输入价格' },
				{ 
					validateFunction: (rule, value, data, callback) => {
						if (value !== '' && (!/^\d+(\.\d+)?$/.test(value) || parseFloat(value) < 0)) {
							callback('价格必须为非负数');
						}
						return true;
					}
				}
			]
		},
		room_type: {
			rules: [{ required: true, errorMessage: '请输入户型' }]
		}
	};
	
	const uForm = ref(null);
	const fileList = ref([]);
	const roomId = ref('');
	const roomInfo = ref(null);
	const roomImagesLoaded = ref(false);
	const token = ref(''); // 定义token变量
	
	// 生命周期
	onMounted(() => {
		getToken(); // 获取token
		
		const params = uni.getLaunchOptionsSync().query || {};
		const page = getCurrentPages().pop();
		
		if (page && page.options) {
			roomId.value = page.options.id;
		} else if (params.id) {
			roomId.value = params.id;
		}
		
		if (roomId.value) {
			form.room_id = roomId.value;
			initRoomData();
		} else {
			uni.showToast({
				title: '缺少房间ID',
				icon: 'none'
			});
			
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
	});
	
	// 获取token
	const getToken = () => {
		token.value = uni.getStorageSync('uni_id_token') || '';
	};
	
	// 初始化房间信息
	const initRoomData = async () => {
		uni.showLoading({
			title: '加载中'
		});
		
		try {
			const res = await uniCloud.callFunction({
				name: 'get-room-detail',
				data: {
					room_id: roomId.value
				},
				getAuthInfo: true
			});
			
			if (res.result.code === 0) {
				roomInfo.value = res.result.data;
				
				// 加载表单数据
				form.room_id = roomInfo.value._id;
				form.room_number = roomInfo.value.room_number;
				form.price = roomInfo.value.price.toString();
				form.room_type = roomInfo.value.room_type;
				form.introduction = roomInfo.value.introduction || '';
				
				// 加载家具列表
				if (roomInfo.value.furniture_list && roomInfo.value.furniture_list.length > 0) {
					form.furniture_list = [...roomInfo.value.furniture_list];
				}
				
				// 加载图片列表
				if (roomInfo.value.images && roomInfo.value.images.length > 0) {
					form.images = [...roomInfo.value.images];
					
					// 构建文件列表显示
					fileList.value = roomInfo.value.images.map((fileID, index) => {
						return {
							url: fileID,
							name: `图片${index + 1}`,
							status: 'success'
						};
					});
					
					roomImagesLoaded.value = true;
				}
			} else {
				uni.showToast({
					title: res.result.message || '获取房间信息失败',
					icon: 'none'
				});
				
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		} catch (e) {
			console.error('获取房间信息失败', e);
			uni.showToast({
				title: '获取房间信息失败',
				icon: 'none'
			});
			
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		} finally {
			uni.hideLoading();
		}
	};
	
	// 上传图片后回调
	const afterRead = async (e) => {
		const file = e.file;
		if (!file) return;
		
		try {
			uni.showLoading({
				title: '上传中'
			});
			
			// 生成唯一的文件名
			const fileExtension = file.url.split('.').pop();
			const cloudPath = `room-images/${Date.now()}-${Math.random().toString(36).slice(-8)}.${fileExtension}`;
			
			// 调用uniCloud的上传文件API
			const result = await uniCloud.uploadFile({
				filePath: file.url,
				cloudPath: cloudPath
			});
			
			// 将返回的fileID添加到表单数据中
			form.images.push(result.fileID);
			
			// 更新文件列表显示
			fileList.value.push({
				url: result.fileID,
				name: cloudPath.split('/').pop(),
				status: 'success'
			});
			
			uni.showToast({
				title: '上传成功',
				icon: 'success'
			});
		} catch (e) {
			console.error('图片上传失败', e);
			uni.showToast({
				title: '图片上传失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};
	
	// 删除图片
	const deleteImage = async (e) => {
		const index = e.index;
		const fileID = form.images[index];
		
		try {
			uni.showLoading({
				title: '删除中'
			});
			
			// 从表单和显示列表中先移除
			form.images.splice(index, 1);
			fileList.value.splice(index, 1);
			
			// 调用云函数删除云存储中的图片
			try {
				// 确保token是最新的
				getToken();
				await uniCloud.callFunction({
					name: 'delete-room-image',
					data: {
						fileID: fileID,
						token: token.value
					}
				});
				
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				});
			} catch (fileError) {
				console.error('删除云存储图片失败', fileError);
				uni.showToast({
					title: '图片已从表单移除',
					icon: 'none'
				});
			}
		} catch (e) {
			console.error('删除图片失败', e);
			uni.showToast({
				title: '删除失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};
	
	// 添加家具项
	const addFurniture = () => {
		form.furniture_list.push('');
	};
	
	// 删除家具项
	const deleteFurniture = (index) => {
		form.furniture_list.splice(index, 1);
	};
	
	// 提交表单
	const submitForm = () => {
		if (!uForm.value) {
			console.error('表单引用不存在');
			uni.showToast({
				title: '表单验证失败',
				icon: 'none'
			});
			return;
		}
		
		uForm.value.validate().then(async res => {
			uni.showLoading({
				title: '保存中'
			});
			
			try {
				const price = parseFloat(form.price);
				
				// 确保token是最新的
				getToken();
				
				if (!token.value) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				
				// 调用编辑房间的云函数
				const res = await uniCloud.callFunction({
					name: 'update-room',
					data: {
						room_id: form.room_id,
						room_number: form.room_number,
						price: price,
						room_type: form.room_type,
						images: form.images,
						furniture_list: form.furniture_list.filter(item => item.trim() !== ''),
						introduction: form.introduction,
						token: token.value
					},
					getAuthInfo: true // 自动传递用户token给云函数
				});
				
				if (res.result.code === 0) {
					uni.showToast({
						title: '房间信息更新成功',
						icon: 'success'
					});
					
					// 延迟返回
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.result.message,
						icon: 'none'
					});
				}
			} catch (e) {
				console.error('更新房间失败', e);
				uni.showToast({
					title: '更新房间失败',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		}).catch(err => {
			console.log('表单验证失败', err);
		});
	};
</script>

<style lang="scss" scoped>
	.content {
		padding: 20px;
	}
	
	.form-container {
		background-color: #ffffff;
		border-radius: 10px;
		padding: 20px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
		margin-bottom: 30px;
	}
	
	.upload-box {
		margin-top: 10px;
	}
	
	.furniture-box {
		.furniture-item {
			display: flex;
			align-items: center;
			margin-bottom: 10px;
			
			.delete-btn {
				margin-left: 10px;
				padding: 5px;
			}
		}
		
		.add-btn {
			margin-top: 10px;
			font-size: 14px;
		}
	}
	
	.submit-btn {
		margin-top: 30px;
		
		button {
			width: 100%;
		}
	}
</style> 